﻿Imports WiremetModel.Entities.OEM
Imports WiremetModel.Entities
Imports System.Globalization

Public Class WireCertificateWireSelectionDialog

    Private _shipment As Wysylka
    Private _orderLine As PozycjaZlecenia
    Private _material As Material
    Private _wiresList As IList(Of Tracking.Drut)
    Private _previousForm As Form
    Private _wireCertificate As WireCertificate
    Private _unitOfWork As UnitOfWork

    Private _goodColor As Color = Color.PaleGreen, _badColor As Color = Color.MistyRose, _wireRowSelection As Color = Color.LightSkyBlue
    Private _wytrzymaloscZleceniaMin, _wytrzymaloscZleceniaMax, _wydluzenieZlecenia, _wymiarZlecenia, _tolDolnaZlecenia, _tolGornaZlecenia, _wymiarMinZlecenia, _wymiarMaxZlecenia As Double

    Sub New(ByVal shipment As Wysylka, ByVal orderLine As PozycjaZlecenia, ByVal material As Material, ByVal wiresList As IList(Of Tracking.Drut), ByVal wireCertificate As WireCertificate, ByRef previousForm As Form, ByRef unitOfWork As UnitOfWork)
        InitializeComponent()

        _shipment = shipment
        _orderLine = orderLine
        _material = material
        _wiresList = wiresList
        _previousForm = previousForm
        _wireCertificate = wireCertificate
        _unitOfWork = unitOfWork


        Double.TryParse(_orderLine.WytrzymaloscMin, _wytrzymaloscZleceniaMin)
        Double.TryParse(_orderLine.WytrzymaloscMax, _wytrzymaloscZleceniaMax)
        Double.TryParse(_orderLine.Wydluzenie, _wydluzenieZlecenia)
        Double.TryParse(_orderLine.Wymiar, _wymiarZlecenia)
        Double.TryParse(_orderLine.TolDolna, _tolDolnaZlecenia)
        Double.TryParse(_orderLine.TolGorna, _tolGornaZlecenia)
        _wymiarMinZlecenia = _wymiarZlecenia + _tolDolnaZlecenia
        _wymiarMaxZlecenia = _wymiarZlecenia + _tolGornaZlecenia

        RefreshZlecenieInfo(orderLine.Zlecenie)
        RefreshPozycjaZleceniaInfo(orderLine, material)
        RefreshWiresTable(wiresList)
    End Sub

    Private Sub WireCertificateWireSelectionDialog_Load(sender As Object, e As EventArgs) Handles Me.Load
        dgv_Wire.ClearSelection()
    End Sub


    Private Sub RefreshZlecenieInfo(ByVal zlecenie As Zlecenie)

        gb_ZlecenieInfo.Text = zlecenie.Klient.NazwaSkrocona + " - " + zlecenie.Numer
        txt_DataUtworzenia.Text = zlecenie.DataUtworzenia.ToShortDateString()
        txt_TerminRealizacji.Text = zlecenie.Termin.ToShortDateString()
        txt_Uwagi.Text = zlecenie.Uwagi

    End Sub

    Private Sub RefreshPozycjaZleceniaInfo(ByVal orderLine As PozycjaZlecenia, ByVal material As Material)

        gb_PozycjaZlecenia.Text = "Pozycja - #" + orderLine.NumerPozycji.ToString()
        txt_Wymiar.Text = orderLine.Wymiar.ToString()
        txt_Gatunek.Text = orderLine.Gatunek.NazwaAng
        txt_Wytop.Text = material.Wytop
        txt_TolDolna.Text = orderLine.TolDolna
        txt_TolGorna.Text = orderLine.TolGorna

        txt_Wydluzenie.Text = orderLine.Wydluzenie
        txt_Pakowanie.Text = orderLine.Pakowanie.Nazwa
        txt_WytrzymaloscMin.Text = orderLine.WytrzymaloscMin.ToString()
        txt_WytrzymaloscMax.Text = orderLine.WytrzymaloscMax.ToString()

    End Sub


    Private Sub RefreshWiresTable(ByVal wiresList As IList(Of Tracking.Drut))

        dgv_Wire.Rows.Clear()
        For Each drut As Tracking.Drut In wiresList

            Dim drutId As Integer = drut.Id
            Dim kontrola As Tracking.Kontrola = drut.Kontrola.First()
            Dim certificateChecked As Boolean = _wireCertificate IsNot Nothing AndAlso _wireCertificate.MechanicalParameters.Any(Function(x) x.WireId = drutId.ToString())
            Dim rowIndex As Integer = dgv_Wire.Rows.Add(
                drut.Id,
                certificateChecked,
                kontrola.Pakowanie.Nazwa,
                kontrola.Ilosc.ToString() + " " + _orderLine.JednostkaMiary.Jednostka,
                kontrola.ZwickPomiar,
                kontrola.ZwickSila,
                kontrola.ZwickProcentWydluzenia,
                kontrola.ZwickWytrzymalosc,
                kontrola.WymiarMin,
                kontrola.WymiarMax
            )
            dgv_Wire.Rows(rowIndex).Tag = drut

            IndicateProductionResult(rowIndex)

            If certificateChecked Then
                dgv_Wire.Rows(rowIndex).DefaultCellStyle.BackColor = _wireRowSelection
                dgv_Wire.Rows(rowIndex).DefaultCellStyle.SelectionBackColor = _wireRowSelection
            End If
        Next
    End Sub

    Private Sub IndicateProductionResult(rowIndex As Integer)

        Dim drut As Tracking.Drut = CType(dgv_Wire.Rows(rowIndex).Tag, Tracking.Drut)
        Dim kontrola As Tracking.Kontrola = drut.Kontrola.First()

        If _wytrzymaloscZleceniaMin <> 0 AndAlso _wytrzymaloscZleceniaMax <> 0 Then
            If kontrola.ZwickWytrzymalosc < _wytrzymaloscZleceniaMin OrElse kontrola.ZwickWytrzymalosc > _wytrzymaloscZleceniaMax Then
                SetCellColorInvalid(rowIndex, "WireEndurance")
            Else
                SetCellColorValid(rowIndex, "WireEndurance")
            End If
        End If

        If _wydluzenieZlecenia <> 0 Then
            If kontrola.ZwickProcentWydluzenia < _wydluzenieZlecenia OrElse
                kontrola.ZwickProcentWydluzenia > _wydluzenieZlecenia Then

                SetCellColorInvalid(rowIndex, "WireElongation")
            Else
                SetCellColorValid(rowIndex, "WireElongation")
            End If
        End If

        If _wymiarZlecenia <> 0 Then
            If kontrola.WymiarMin / 1000.0 < _wymiarMinZlecenia OrElse kontrola.WymiarMin / 1000.0 > _wymiarMaxZlecenia Then
                SetCellColorInvalid(rowIndex, "WymiarMin")
            Else
                SetCellColorValid(rowIndex, "WymiarMin")
            End If

            If kontrola.WymiarMax / 1000.0 < _wymiarMinZlecenia OrElse kontrola.WymiarMax / 1000.0 > _wymiarMaxZlecenia Then
                SetCellColorInvalid(rowIndex, "WymiarMax")
            Else
                SetCellColorValid(rowIndex, "WymiarMax")
            End If
        End If
    End Sub

    Private Sub SetCellColorValid(rowIndex As Integer, columnName As String)
        dgv_Wire.Rows(rowIndex).Cells(columnName).Style.BackColor = _goodColor
        dgv_Wire.Rows(rowIndex).Cells(columnName).Style.SelectionBackColor = _goodColor
    End Sub

    Private Sub SetCellColorInvalid(rowIndex As Integer, columnName As String)
        dgv_Wire.Rows(rowIndex).Cells(columnName).Style.BackColor = _badColor
        dgv_Wire.Rows(rowIndex).Cells(columnName).Style.SelectionBackColor = _badColor
    End Sub

    Private Sub dgv_Wire_CellClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgv_Wire.CellClick

        Dim checked As Boolean = CType(dgv_Wire.Rows(e.RowIndex).Cells("WireChecked").Value, Boolean)
        checked = Not checked

        dgv_Wire.Rows(e.RowIndex).Cells("WireChecked").Value = checked
        If checked Then
            dgv_Wire.Rows(e.RowIndex).DefaultCellStyle.BackColor = _wireRowSelection
            dgv_Wire.Rows(e.RowIndex).DefaultCellStyle.SelectionBackColor = _wireRowSelection
        Else
            dgv_Wire.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.White
            dgv_Wire.Rows(e.RowIndex).DefaultCellStyle.SelectionBackColor = Color.White
            IndicateProductionResult(e.RowIndex)
        End If
    End Sub


    Private Function GetWiresList() As IDictionary(Of Tracking.Drut, Boolean)
        Dim wires As New Dictionary(Of Tracking.Drut, Boolean)
        For Each row As DataGridViewRow In dgv_Wire.Rows
            wires.Add(CType(row.Tag, Tracking.Drut), CType(row.Cells("WireChecked").Value, Boolean))
        Next
        Return wires
    End Function

    Private Sub EnsureWireIsSelected()
        For Each row As DataGridViewRow In dgv_Wire.Rows
            If CType(row.Cells("WireChecked").Value, Boolean) Then
                Return
            End If
        Next
        Throw New Exception("Proszę, wybierz drut, aby kontynuować.")
    End Sub

    Private Sub btn_Accept_Click(sender As System.Object, e As System.EventArgs) Handles btn_Accept.Click
        Try
            EnsureWireIsSelected()
            Dim printingDialog As New WireCertificatePrintingDialog(_shipment, _orderLine, _material, GetWiresList(), Me, _wireCertificate, _unitOfWork)
            Me.Hide()
            printingDialog.ShowDialog()

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub btn_Cancel_Click(sender As System.Object, e As System.EventArgs) Handles btn_Cancel.Click
        _previousForm.Show()
    End Sub


End Class